﻿// ===============================================================================
// Project Name        :    Gfw.BLL.Basic.Stock
// Project Description :    
// ===============================================================================
// Class Name          :    UsAccountLogic
// Namespace:          :    Gfw.BLL.Basic.Stock
// Class Version       :    v1.0.0.0
// Class Description   :    
// CLR Version:        :    4.0.30319.17626
//Author               :    lif
// Machine             :    ADICO-PC
// Create Time         :    2012/7/14 11:00:08
// Update Time         :    2012/7/14 11:00:08
// ===============================================================================
// Copyright © lif 2012 . All rights reserved.
// ===============================================================================
using System;
using System.Collections.Generic;
using Gfw.BLL.Basic.Stock.Facilities;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Infrastructure.Stock.Enums;
using Gfw.Infrastructure.Stock.Facilities;
using Gfw.Models.Stock;
using Gfw.Repositories.Stock;
using Gfw.Repository;
using Gfw.Web.Models.Stock;

namespace Gfw.BLL.Basic.Stock
{

    /// <summary>
    /// 用户股票帐户逻辑
    /// </summary>
    public static class UsAccountLogic
    {
        #region 用户帐户操作

        public static void NewUserAccount(string userId, UnitOfWork work)
        {
            StkUseraccount account = new StkUseraccount()
                                         {
                                             UserId = userId,
                                             ActivationDate = null,
                                             IsLock = (int)AccountLockEnum.Normal,
                                             MaxOwnedMoney = StockConfig.UserInitilizeMaxOwnedMoney,
                                             OriginalStockCount = 0,
                                             StockCount = 0,
                                             StockMoney = 0
                                         };
            UserAccountRepository rep = new UserAccountRepository();
            rep.Save(account, work);
        }


        #endregion

        #region 用户概述

        public static UserAccountModel GetUserAccount(string userId)
        {
            UserAccountRepository rep = new UserAccountRepository();
            var account = rep.Get(userId);
            if (account == null)
                throw new GfwException("未找到用户的游戏帐户，改用户可能未激活。");
            var model = new UserAccountModel()
                            {
                                MarketValue = account.StockCount * StockManager.CurrentPrice,
                                MaxOwnedMoney = account.MaxOwnedMoney,
                                OriginalStockCount = account.OriginalStockCount,
                                OwnedCount = account.StockCount,
                                StockMoney = account.StockMoney,
                                UserId = userId
                            };
            model.Total = model.MarketValue + model.StockMoney;
            return model;
        }

        #endregion

        #region 币种转换电子币转换到股票币
        public static void ToSCurrency(string userId, decimal count)
        {
            ToStockMoneyFacilityImpl facility = new ToStockMoneyFacilityImpl(userId, count);
            facility.Execute();
        }

        #endregion

        #region 股票操作

        #region 买入股票
        public static BuyModel GetBuyModel(string userId)
        {
            BuyModel model = new BuyModel();
            if (!StockManager.ServcieIsRunning())
            {
                model.CanBuy = false;
                return model;
            }
            model.CanBuy = StockManager.GetMarketState() != (int)MarketRunningStateEnum.Off;
            if (model.CanBuy)
            {
                UserAccountRepository rep = new UserAccountRepository();
                var account = rep.Get(userId);
                var price = StockManager.CurrentPrice;

                model.Balance = account.StockMoney;
                model.BuyCount = 0;
                model.CurrentPrice = price;
                model.MaxCount = Math.Floor((account.StockMoney / (price * 100))) * 100;
            }
            return model;
        }

        public static void Buy(string userId, decimal count, decimal price)
        {
            BuyTradeFacility bf = new BuyTradeFacilityImpl(userId, count, price,ForceTradeTypeEnum.Normal);
            bf.Execute();
        }

        #endregion

        #region 卖出股票
        public static SellModel GetSellModel(string userId)
        {
            SellModel model = new SellModel();
            if (!StockManager.ServcieIsRunning())
            {
                model.CanSell = false;
                return model;
            }
            model.CanSell = StockManager.GetMarketState() == (int) MarketRunningStateEnum.Normal;
            if (model.CanSell)
            {

                UserAccountRepository rep = new UserAccountRepository();
                var account = rep.Get(userId);

                var price = StockManager.CurrentPrice;

                //如果不是第一个0.0658以上价格，则不能卖出
                if (price < account.LastAutoSellPrice)
                    model.CanSell = false;


                model.SellCount = 0;
                model.CurrentPrice = price;
                model.MaxCount = account.StockCount;
            }
            return model;
        }

        public static void Sell(string userId, decimal count, decimal price)
        {
            SellTradeFacility sf = new SellTradeFacilityImpl(userId, count, price);
            sf.Execute();
        }

        #endregion

        #region 撤单
        public static IList<AgencyModel> GetCanCancelAgencyModelList(string userId)
        {
            BargainAgencyRepository rep = new BargainAgencyRepository();
            var list = rep.GetByTradeStatusNotEq((int)TradeStatusEnum.Done, userId);
            var result = new List<AgencyModel>();
            foreach (var l in list)
            {
                result.Add(new AgencyModel()
                               {
                                   AgencyId = l.Id,
                                   AgenceCount = l.AgencyCount,
                                   AgenceDate = l.AgencyDate,
                                   AgencePrice = l.AgencyPrice,
                                   TradeCount = l.TradeCount,
                                   TradeStatus = l.TradeStatus,
                                   TradeType = l.TradeType,
                                   ForceType = l.ForceTradeType
                               });
            }
            return result;
        }

        public static void CancelTrade(string agencyId)
        {
            StockManager.CancelTrade(agencyId);
        }

        #endregion

        #endregion

        #region 交易记录查询
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="pageIndex">Based:1</param>
        /// <param name="pageSize"></param>
        /// <param name="pageTotal"></param>
        /// <returns></returns>
        public static IList<BargainRecordModel> BargainReocrdQuery(string userId, DateTime? startDate, DateTime? endDate,
            int pageIndex, int pageSize, out int pageTotal)
        {
            pageTotal = 0;
            BargainRecordRepository rep = new BargainRecordRepository();
            //if (pageIndex <= 1)
            {
               // pageIndex = 1;
                pageTotal = rep.QueryCount(userId, startDate, endDate);
                pageTotal = (pageTotal + pageSize - 1) / pageSize;
            }
            var list = rep.Query(userId, startDate, endDate, pageIndex  * pageSize, pageSize);
            var result = new List<BargainRecordModel>();
            foreach (var l in list)
            {
                result.Add(l.CopyTo<BargainRecordModel>());
            }
            return result;
        }

        #endregion


    }
}
